package com.faner.fast.activiti.view;

import cn.hutool.core.util.StrUtil;
import com.faner.fast.base.PageDTO;
import com.faner.fast.exception.FailedException;
import com.faner.fast.upms.model.SysUserDO;
import com.faner.fast.upms.service.SysRoleService;
import com.faner.fast.upms.service.SysUserService;
import com.faner.fast.util.PageUtil;
import com.faner.fast.util.R;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.persistence.entity.ModelEntityImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.apache.batik.util.SoftReferenceCache;
/**
 * <p>
 * activiti编辑器
 * </p>
 *
 * @author faner
 * @since 2021-02-25
 */
@Api(value = "activiti编辑器", tags = "activiti-编辑器模块")
@ApiSupport(order = 100)
@Slf4j
@RestController
@AllArgsConstructor
public class ModelEditorJsonRestResource implements ModelDataJsonConstants {

  private RepositoryService repositoryService;
  private ObjectMapper objectMapper;
  private SysUserService sysUserService;
  private SysRoleService sysRoleService;

  /**
   * 流程设计模型部署表act_re_model
   * 获取流程设计模型json数据
   * @param modelId
   * @return
   */
  @ApiOperation(value = "获取流程设计模型json数据")
  @ApiOperationSupport(order = 10,author = "faner")
  @GetMapping(value="/activiti/model/{modelId}/json", produces = "application/json")
  public ObjectNode getEditorJson(@PathVariable String modelId) {
    ObjectNode modelNode = null;
    Model model = repositoryService.getModel(modelId);
    if (model != null) {
      try {
        if (StrUtil.isNotEmpty(model.getMetaInfo())) {
          modelNode = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
        } else {
          modelNode = objectMapper.createObjectNode();
          modelNode.put(MODEL_NAME, model.getName());
        }
        modelNode.put(MODEL_ID, model.getId());
        ObjectNode editorJsonNode = (ObjectNode) objectMapper.readTree(
            new String(repositoryService.getModelEditorSource(model.getId()), StandardCharsets.UTF_8));
        modelNode.put("model", editorJsonNode);

      } catch (Exception e) {
        log.error("Error creating model JSON", e);
        throw new ActivitiException("Error creating model JSON", e);
      }
    }
    return modelNode;
  }

  /**
   * 跳转到新增编辑页面
   */
  @ApiOperation(value = "跳转到新增编辑页面")
  @ApiOperationSupport(order = 20,author = "faner")
  @PostMapping(value="/activiti/model/{modelId}/save")
  @ResponseStatus(value = HttpStatus.OK)
  public void saveModel(@PathVariable String modelId, @RequestBody MultiValueMap<String, String> values) {
    try {
      Model model = repositoryService.getModel(modelId);

      ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());

      modelJson.put(MODEL_NAME, values.getFirst("name"));
      modelJson.put(MODEL_DESCRIPTION, values.getFirst("description"));
      model.setMetaInfo(modelJson.toString());
      model.setName(values.getFirst("name"));

      repositoryService.saveModel(model);

      repositoryService.addModelEditorSource(model.getId(), values.getFirst("json_xml").getBytes(StandardCharsets.UTF_8));

      InputStream svgStream = new ByteArrayInputStream(values.getFirst("svg_xml").getBytes(StandardCharsets.UTF_8));
      TranscoderInput input = new TranscoderInput(svgStream);

      PNGTranscoder transcoder = new PNGTranscoder();
      // Setup output
      ByteArrayOutputStream outStream = new ByteArrayOutputStream();
      TranscoderOutput output = new TranscoderOutput(outStream);

      // Do the transformation
      transcoder.transcode(input, output);
      final byte[] result = outStream.toByteArray();
      repositoryService.addModelEditorSourceExtra(model.getId(), result);
      outStream.close();

    } catch (Exception e) {
      log.error("保存流程模型失败，错误信息:{}", e);
      throw new ActivitiException("Error saving model", e);
    }
  }


    /**
     * 模型列表
     */
    @ApiOperation(value = "模型列表")
    @ApiOperationSupport(order = 30,author = "faner")
    @GetMapping("/activiti/process/model/datagrid")
    public R list(ModelEntityImpl modelEntity,  @Validated PageDTO page) {
        ModelQuery modelQuery = repositoryService.createModelQuery();
        modelQuery.orderByLastUpdateTime().desc();
        // 条件过滤
        if (StrUtil.isNotBlank(modelEntity.getKey())) {
            modelQuery.modelKey(modelEntity.getKey());
        }
        if (StrUtil.isNotBlank(modelEntity.getName())) {
            modelQuery.modelNameLike("%" + modelEntity.getName() + "%");
        }
        Integer pageNum = page.getPageNum().intValue();
        Integer pageSize = page.getPageSize().intValue();
        List<Model> resultList = modelQuery.listPage((pageNum - 1) * pageSize, pageSize);

        List<ModelEntityImpl> list = new ArrayList<>();
        resultList.parallelStream().forEach(model -> {
            ModelEntityImpl modelEntity1 = (ModelEntityImpl) model;
            list.add(modelEntity1);
        });
       return R.ok(PageUtil.toPage(list,pageNum,pageSize,modelQuery.count()));

    }


  /**
   * 创建模型
   */
  @ApiOperation(value = "创建模型")
  @ApiOperationSupport(order = 40,author = "faner")
  @PostMapping(value = "/activiti/process/model/create")
  public R create(@RequestParam(value = "name") String name,
                  @RequestParam(value = "key") String key,
                  @RequestParam(value = "description", required = false) String description) {
    Model newModel = repositoryService.newModel();
    try {
      ObjectMapper objectMapper = new ObjectMapper();
      ObjectNode editorNode = objectMapper.createObjectNode();
      editorNode.put("id", "canvas");
      editorNode.put("resourceId", "canvas");
      ObjectNode stencilSetNode = objectMapper.createObjectNode();
      stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
      editorNode.put("stencilset", stencilSetNode);

      ObjectNode modelObjectNode = objectMapper.createObjectNode();
      modelObjectNode.put(MODEL_NAME, name);
      modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
      description = StringUtils.defaultString(description);
      modelObjectNode.put(MODEL_DESCRIPTION, description);

//      Model newModel = repositoryService.newModel();
      newModel.setMetaInfo(modelObjectNode.toString());
      newModel.setName(name);
      newModel.setKey(StringUtils.defaultString(key));

      repositoryService.saveModel(newModel);
      repositoryService.addModelEditorSource(newModel.getId(), editorNode.toString().getBytes(StandardCharsets.UTF_8));
    } catch (Exception e) {
      log.error("创建模型失败：", e);
      throw new FailedException("创建模型失败");
    }
    return R.ok(newModel.getId(),"创建模型成功");
  }

  /**
   * 根据Model部署流程
   */
  @ApiOperation(value = "根据ModelId部署流程")
  @ApiOperationSupport(order = 50,author = "faner")
  @PostMapping(value = "/activiti/process/model/deploy")
  @ResponseBody
  public R deploy(@RequestParam("modelId") String modelId) {
    try {
      Model modelData = repositoryService.getModel(modelId);
      ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
      byte[] bpmnBytes = null;

      BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
      bpmnBytes = new BpmnXMLConverter().convertToXML(model);

      byte[] bytes = repositoryService.getModelEditorSourceExtra(modelData.getId());

      String processName = modelData.getName() + ".bpmn20.xml";
      //Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes, "UTF-8")).deploy();
      Deployment deployment = repositoryService.createDeployment().name(modelData.getName())
              .addBytes(modelData.getName() + ".png", bytes)
              .addString(processName, new String(bpmnBytes)).deploy();
      /**
       * 如果新增部署，则查询流程管理表，如果key相同，则设置为过期
       */
//      ProcessDefinition pd = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
//      QueryWrapper<WorkflowMngEntity> queryWrapper = new QueryWrapper<WorkflowMngEntity>();
//      queryWrapper.eq("PROCESS_KEY", pd.getKey());
//      List<WorkflowMngEntity> lstResult = workflowMngService.list(queryWrapper);
//      if(null != lstResult && lstResult.size() > 0) {
//        for(WorkflowMngEntity mng : lstResult) {
//          mng.setStatus("2");
//          workflowMngService.saveOrUpdate(mng);
//        }
//      }
      log.info("部署成功，部署ID=" + deployment.getId());
    } catch (Exception e) {
      log.error("根据模型部署流程失败：modelId={}", modelId, e);
      throw new FailedException("根据模型部署流程失败");
    }
    return R.ok("部署成功");
  }

  /**
   * 导出model的xml文件
   */
  @ApiOperation(value = "导出model的xml文件")
  @ApiOperationSupport(order = 60,author = "faner")
  @GetMapping(value = "/activiti/process/model/export")
  public void export(@RequestParam("modelId") String modelId, HttpServletResponse response) {
    try {
      Model modelData = repositoryService.getModel(modelId);
      BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
      JsonNode editorNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
      BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);

      // 流程非空判断
      if (!CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
        BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
        byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);

        ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
        String filename = bpmnModel.getMainProcess().getId() + ".bpmn";
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        IOUtils.copy(in, response.getOutputStream());
        response.flushBuffer();
      }
    } catch (Exception e) {
      log.error("导出model的xml文件失败：modelId={}", modelId, e);
    }
  }

  @ApiOperation(value = "删除指定模型")
  @ApiOperationSupport(order = 70,author = "faner")
  @PostMapping("/activiti/process/model/remove")
  @SneakyThrows
  public R remove(@RequestParam String modelId) {
    repositoryService.deleteModel(modelId);
    return R.ok();
  }


//  /**
//   * 免登录访问用户列表
//   * @param user
//   * @return
//   */
//  @GetMapping("/list")
//  public R list(SysUserDO user)
//  {
//    List<SysUserDO> list = sysUserService.;
//    return getDataTable(list);
//  }
//
//  /**
//   * 角色列表
//   * @param role
//   * @return
//   */
//  @GetMapping("/modeler/role/list")
//  public R list(SysRole role)
//  {
//    List<SysRole> list = roleService.selectRoleList(role);
//    return R.ok(list);
//  }
//
//  /**
//   * 某角色下的用户列表
//   * @param roleKey
//   * @return
//   */
//  @GetMapping("/modeler/user/listByRoleKey")
//  public TableDataInfo list(String roleKey)
//  {
//    startPage();
//    List<SysUser> list = userMapper.selectUserListByRoleKey(roleKey);
//    return getDataTable(list);
//  }

}
